<template>
  <el-card style="min-height: 700px">
    <h2>创建订单</h2>
    <el-form :model="form" label-width="80px">
      <el-form-item label="用户">
        <el-select
          v-model="form.userId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入用户名称搜索"
          :remote-method="fetchUsers"
          :loading="userLoading"
          style="width: 400px"
          @change="onUserChange"
        >
          <el-option
            v-for="user in users"
            :key="user.userId"
            :label="user.name"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品">
        <el-select
          v-model="selectedProductId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入商品标题或编码搜索"
          :remote-method="fetchProducts"
          :loading="productLoading"
          style="width: 400px"
          @change="onProductChange"
        >
          <el-option
            v-for="product in products"
            :key="product.skuId"
            :label="`${product.skuCode} ${product.title}`"
            :value="product.skuId"
          />
        </el-select>
        <el-button type="primary" style="margin-left: 5px" @click="addProduct">选中</el-button>
      </el-form-item>
      <div style="margin-left: 30px">
        <el-table stripe :data="form.orderItems" style="width: 100%" border>
          <el-table-column prop="skuId" label="skuId" width="80" />
          <el-table-column prop="skuCode" label="skuCode" />
          <el-table-column prop="mainImg" label="商品图片" width="100">
            <template v-slot="scope">
              <el-image
                :src="scope.row.mainImg"
                style="width: 80px; height: 80px"
                fit="cover"
                :preview-src-list="[scope.row.mainImg]"
                preview-teleported
              >
                <template v-slot:error>
                  <div class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="商品标题" />
          <el-table-column prop="attributes" label="属性" />
          <el-table-column prop="crossedPrice" label="划线价" width="100" />
          <el-table-column prop="price" label="价格" width="100" />
          <el-table-column prop="qty" label="数量" width="120" fixed="right">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.qty" :min="1" style="width: 100px" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" fixed="right">
            <template v-slot="scope">
              <el-input type="textarea" v-model="scope.row.remark" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template v-slot="scope">
              <el-button @click="removeItem(scope.$index)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin: 20px 0 0 30px; font-weight: bold"> 合计：¥{{ totalAmount }} </div>
      <el-form-item label="备注" style="margin-top: 20px">
        <el-input type="textarea" v-model="form.remark" style="width: 400px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitOrder">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getPageList as getUserPageList } from '@/api/user/admin'
import { getPageList as getProductPageList } from '@/api/product/admin'
import { placeOrder } from '@/api/order/admin'
import { useRouter } from 'vue-router'

export default {
  setup() {
    const users = ref([])
    const products = ref([])
    const userLoading = ref(false)
    const productLoading = ref(false)
    const selectedProductId = ref(null)
    const router = useRouter()

    const form = ref({
      userId: null,
      orderItems: [],
      remark: ''
    })

    // 计算合计金额
    const totalAmount = computed(() => {
      return form.value.orderItems
        .reduce((total, item) => {
          return total + (item.price || 0) * (item.qty || 0)
        }, 0)
        .toFixed(2)
    })

    const fetchUsers = async (query) => {
      userLoading.value = true
      try {
        const response = await getUserPageList({
          keywords: query,
          status: 1,
          pageSize: 10,
          pageNum: 1
        })
        users.value = response.data.list || []
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      } finally {
        userLoading.value = false
      }
    }

    const fetchProducts = async (query) => {
      productLoading.value = true
      try {
        const response = await getProductPageList({ keyword: query, pageSize: 10, pageNum: 1 })
        products.value = response.data.list || []
      } catch (error) {
        ElMessage.error('获取商品列表失败')
      } finally {
        productLoading.value = false
      }
    }

    const onUserChange = (value) => {
      form.value.userId = value
    }

    const onProductChange = (value) => {
      selectedProductId.value = value
    }

    const formatAttributes = (attrValueList) => {
      if (!attrValueList || attrValueList.length === 0) {
        return '无属性信息'
      }
      return attrValueList.map((attr) => `${attr.pnValue}:${attr.pvValue}`).join('，')
    }

    const addProduct = () => {
      if (!selectedProductId.value) return
      const product = products.value.find((p) => p.skuId === selectedProductId.value)
      if (!product) return
      form.value.orderItems.push({
        skuId: product.skuId,
        skuCode: product.skuCode,
        title: product.title,
        attributes: formatAttributes(product.attrValueList),
        crossedPrice: product.crossedPrice,
        price: product.price,
        mainImg: product.mainImg,
        qty: 1,
        remark: ''
      })
      selectedProductId.value = null
    }

    const removeItem = (index) => {
      form.value.orderItems.splice(index, 1)
    }

    const submitOrder = async () => {
      if (!form.value.userId) {
        ElMessage.error('请选择用户')
        return
      }

      if (form.value.orderItems.length === 0) {
        ElMessage.error('请添加商品')
        return
      }

      try {
        const params = {
          userId: form.value.userId,
          skuList: form.value.orderItems.map((item) => ({
            skuId: item.skuId,
            qty: item.qty,
            remark: item.remark
          })),
          remark: form.value.remark
        }

        const response = await placeOrder(params)
        ElMessage.success('订单创建成功')
        // 跳转到订单详情页面
        router.push({
          name: 'OrderDetail',
          query: { orderNo: response.data.orderNo }
        })
      } catch (error) {
        ElMessage.error('创建订单失败')
      }
    }

    const resetForm = () => {
      form.value = {
        userId: null,
        orderItems: [],
        remark: ''
      }
      users.value = []
      products.value = []
      selectedProductId.value = null
    }

    onMounted(() => {
      // 初始化时不加载数据，等待用户输入搜索
    })

    return {
      users,
      products,
      userLoading,
      productLoading,
      selectedProductId,
      form,
      totalAmount,
      fetchUsers,
      fetchProducts,
      onUserChange,
      onProductChange,
      addProduct,
      removeItem,
      submitOrder,
      resetForm
    }
  }
}
</script>

<style scoped>
/* 添加一些基本样式 */
h2 {
  margin-bottom: 20px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>
